package com.roshan.web.security.util;

import java.net.URI;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;

import com.roshan.util.RoarURISpec;
import com.roshan.web.security.util.constants.SecurityConstants;
import com.roshan.web.util.constants.CommonConstants;

public class CookieUtils {

    public static String getMFACookieName(String defaultMfaCookieName, String customerUri) {

        if (!StringUtils.hasText(defaultMfaCookieName) || !StringUtils.hasText(customerUri)) {
            return null;
        }

        String uriFragment = RoarURISpec.getUUID(URI.create(customerUri));

        if (!StringUtils.hasText(uriFragment) || StringUtils.containsWhitespace(uriFragment)) {
            return null;
        }

        return defaultMfaCookieName + CommonConstants.UNDERSCORE + uriFragment;
    }

    public static String getMFACookieContent(String username, String customerUri) {

        if (!StringUtils.hasText(username) || !StringUtils.hasText(customerUri)) {
            return null;
        }

        return username + SecurityConstants.MFA_COOKIE_DELIMITER + customerUri;
    }

    public static String getCookieValue(String cookieName, HttpServletRequest request) {
        if (request.getCookies() != null && request.getCookies().length > 0) {
            for (Cookie cookie : request.getCookies()) {
                if (cookie.getName().equalsIgnoreCase(cookieName.trim()))
                    return cookie.getValue();
            }
        }
        return null;
    }

    public static Cookie getCookie(String cookieName, HttpServletRequest request) {
        if (request.getCookies() != null && request.getCookies().length > 0) {
            for (Cookie cookie : request.getCookies()) {
                if (cookie.getName().equalsIgnoreCase(cookieName.trim()))
                    return cookie;
            }
        }
        return null;
    }
}
